/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
<div class="planContent" v-if="!!chooseId">
  <div class="mask" v-if="maskVisible" @click ="clickMask"></div>
  <div class="btnGroup" v-show="false">
    <el-button class="btn" type="primary" @click="handleCreate">{{$t('openatccomponents.greenwaveoptimize.generate')}}</el-button>
    <div class="editbtn" :style="{zIndex: zIndexObj.editZIndex}">
      <el-popover placement="top-start" trigger="manual" v-model="maskVisible" width="290">
        <div class="tipContent">
          <div>
            <i class="iconfont icon-yindaoicon1 handicon"></i>
          </div>
          <div class="text">{{$t('openatccomponents.greenwaveoptimize.createconfig')}}</div>
        </div>
        <button slot="reference" class="btn" @click="handleEdit" ref="editbtn">{{$t('openatccomponents.greenwaveoptimize.edit')}}</button>
      </el-popover>
    </div>
    <el-button class="btn" type="primary" @click="Download" style="margin-left:10px;">{{$t('openatccomponents.button.download')}}</el-button>
  </div>
  <el-tabs v-model="activeName" type="card" @tab-click="handleClick" style="border:0px solid red;height:40%;">
    <el-tab-pane :label="$t('openatccomponents.greenwaveoptimize.timespace')" name="first">
      <!-- <PlanChart ref="planchart"/> -->
    </el-tab-pane>
  </el-tabs>
  <el-tabs v-model="activeName2" type="card" @tab-click="handleClick" style="border:0px solid red;height:50%;">
    <el-tab-pane :label="$t('openatccomponents.greenwaveoptimize.pattern')" name="second">
      <!-- <PatternTable ref="patterntable" @onNewPatternListChange="onNewPatternListChange"/> -->
    </el-tab-pane>
  </el-tabs>
  <Messagebox :visible="messageboxVisible" :text="$t('openatccomponents.greenwaveoptimize.confirmdownloadpattern')" @cancle="cancle" @ok="ok"/>
</div>
</template>

<script>
import PatternTable from './pattern/patternTable'
// import PlanChart from './pattern/planChart/index'
import { GetRouteInfo,
  getAllPatternOfDevs, getAllPhaseOfDevs,
  generateRoute, updateRoutePattern, downloadRoutePattern, deleteRoutePattern } from '../../../api/route'
import Messagebox from '../../components/MessageBox/index'
import { getMessageByCode } from '../../../utils/responseMessage'
export default {
  name: 'PlanContent',
  data () {
    return {
      chooseId: 0,
      timer: 0,
      activeName: 'first',
      activeName2: 'second',
      maskVisible: false, // 引导遮罩层是否显示
      configurationVisible: false, // 配置界面是否显示
      messageboxVisible: false, // 关闭界面二期确认弹窗是否显示
      addNum: 0,
      mock: [],
      agentids: [],
      routeData: {}, // 单个协调路线的全部信息
      patternList: [],
      phaseList: [],
      greenwave: []
    }
  },
  components: {
    PatternTable,
    // PlanChart,
    Messagebox
  },
  props: {
    schemeData: {
      type: Array
    },
    step: {
      type: Boolean
    },
    zIndexObj: {
      type: Object
    }
  },
  watch: {
    schemeData: {
      handler: function (val) {
        if (val && !val.length && this.step) {
          this.maskVisible = true
          // 模拟一次手动点击，触发tip显示
          this.$refs.editbtn.click()
        }
      },
      deep: true
    }
  },
  mounted () {
  },
  destroyed () {
    this.closeInterval()
  },
  methods: {
    async init (chooseId, editableTab, agentids) {
      console.log('init planContent edittab', editableTab)
      if (this.agentids.join('') !== agentids.join('')) {
        // reset data
        this.patternList = []
        this.phaseList = []
      }
      this.agentids = agentids
      this.chooseId = chooseId
      // this.getRouteInfo()
      this.routeData = editableTab
      let patternList = this.getPatternListFromTab(editableTab, this.patternList)
      let phaseList = this.getPhaseListFromTab(editableTab, this.phaseList)
      if (patternList && patternList.length > 0 && phaseList && phaseList.length > 0) {
        this.patternList = patternList
        this.phaseList = phaseList
        this.handlePatternTable()
        console.log('use params feature form editableTab', editableTab)
      } else {
        this.getAllPatternOfRoute()
      }
    },
    getPatternListFromTab (tab, list) {
      let res = []
      let devs = tab.devs
      for (let dev of devs) {
        if (!dev.feature || !dev.feature.patternList || dev.feature.patternList.length === 0) {
          res = list
          return res
        }
      }
      let devPatternList = devs.map(item => {
        let pattern = {
          agentid: item.agentid,
          feature: item.feature
        }
        return pattern
      })
      res = devPatternList
      return res
    },
    getPhaseListFromTab (tab, list) {
      let res = []
      let devs = tab.devs
      for (let dev of devs) {
        if (!dev.feature || !dev.feature.phaseList || dev.feature.phaseList.length === 0) {
          res = list
          return res
        }
      }
      let devPhaseList = devs.map(item => {
        let pattern = {
          agentid: item.agentid,
          feature: item.feature
        }
        return pattern
      })
      res = devPhaseList
      return res
    },
    closeInterval () {
      clearInterval(this.timer)
    },
    cancle () {
      this.messageboxVisible = false
    },
    ok () {
      this.messageboxVisible = false
      this.handleDownload()
    },
    Download () {
      this.messageboxVisible = true
    },
    handleClick (tab, event) {
      if (tab.name === 'first') {
        this.refreshChart()
      }
    },
    refreshChart () {
      let patterntable = this.$refs.patterntable
      let newPatternList = patterntable.newPatternList
      for (let pattern of this.patternList) {
        let agentid = pattern.agentid
        let newPattern = newPatternList.filter(npl => npl.agentid === agentid)[0]
        let patternId = newPattern.patternId
        let currPatternList = pattern.feature.patternList
        let currPattern
        if (Array.isArray(currPatternList)) {
          currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
          if (!currPattern) {
            currPattern = currPatternList[0]
          }
        } else {
          currPattern = currPatternList
        }
        currPattern.cycle = newPattern.cycle
        currPattern.offset = newPattern.offset
      }
      this.handlePlanChart()
    },
    handleEdit () {
      if (this.maskVisible && this.addNum <= 1) {
        if (this.addNum === 1) {
          this.maskVisible = false
        }
        this.addNum++
      }
      if (!this.maskVisible) {
        // 获取单个协调路线的全部信息
        // (弹窗取消后，应重新获取静态数据，此处采取中间变量法重新赋值，以触发watch能监听到routeData变化，给弹窗内共有变量configData重新赋值)
        const lastRouteData = JSON.parse(JSON.stringify(this.routeData))
        this.routeData = []
        this.routeData = lastRouteData
        this.configurationVisible = true
      }
    },
    getRouteInfo () {
      if (this.chooseId === 0) return
      GetRouteInfo(this.chooseId).then(res => {
        if (!res.data.success) {
          if (res.data.code === '4003') {
            let agentid = res.data.data.agentid
            this.$message.error(this.$t('openatccomponents.greenwaveoptimize.device') + agentid + this.$t('openatccomponents.greenwaveoptimize.notonline'))
            return
          }
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.routeData = res.data.data
        this.getAllPatternOfRoute() // 获取该路线的所有方案
      })
    },
    async handleDownload (id, routeData) {
      let param = {
        id: id,
        continueOnfailure: routeData.continueOnfailure,
        duration: routeData.duration,
        optPatternList: []
      }
      // check
      let generateData = this.getGenerateParam(routeData)
      for (let dev of routeData.devs) {
        if (!dev.feature) {
          let feature = generateData.devs.filter(item => item.agentid === dev.agentid)[0].feature
          delete feature.phase
          dev.feature = feature
        }
      }
      for (let dev of routeData.devs) {
        if (!dev.feature) {
          this.$message.warning(this.$t('openatccomponents.greenwaveoptimize.errDownloadParam'), dev.agentid)
          return false
        }
      }
      param.optPatternList = [routeData]
      return new Promise((resolve, reject) => {
        downloadRoutePattern(param).then(res => {
          if (!res.data.success) {
            let msg = getMessageByCode(res.data.code, this.$i18n.locale)
            if (res.data.data) {
              let errorCode = res.data.data.errorCode
              if (errorCode) {
                msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
              }
            }
            this.$message.error(msg)
            resolve(res)
          }
          this.$alert(this.$t('openatccomponents.greenwaveoptimize.planissuedsucc'), { type: 'success' })
          resolve(res)
        }).catch(error => {
          this.$message.error(error)
        })
      })
    },
    async handleDelete (param) {
      return new Promise((resolve, reject) => {
        deleteRoutePattern(param).then(res => {
          if (!res.data.success) {
            let msg = getMessageByCode(res.data.code, this.$i18n.locale)
            if (res.data.data) {
              let errorCode = res.data.data.errorCode
              if (errorCode) {
                msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
              }
            }
            this.$message.error(msg)
            resolve(false)
          }
          this.$message.success(this.$t('openatccomponents.common.deletesuccess'))
          this.$parent.getAllPlan()
          resolve(true)
        }).catch(error => {
          this.$message.error(error)
        })
      })
    },
    async handleSave (id, routeData) {
      return new Promise((resolve, reject) => {
        let param = this.getSaveParam(id, routeData)
        updateRoutePattern(param).then(res => {
          if (!res.data.success) {
            let msg = getMessageByCode(res.data.code, this.$i18n.locale)
            if (res.data.data) {
              let errorCode = res.data.data.errorCode
              if (errorCode) {
                msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
              }
            }
            this.$message.error(msg)
            resolve(false)
          }
          this.$message.success(this.$t('openatccomponents.common.savesuccess'))
          this.$parent.getAllPlan()
          resolve(true)
        }).catch(error => {
          this.$message.error(error)
        })
      })
    },
    handleSaveClick (id, routeData) {
      let param = this.getSaveParam(id, routeData)
      updateRoutePattern(param).then(res => {
        if (!res.data.success) {
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            let errorCode = res.data.data.errorCode
            if (errorCode) {
              msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
            }
          }
          this.$message.error(msg)
          return
        }
        this.$message.success(this.$t('openatccomponents.common.savesuccess'))
        this.$parent.getAllPlan()
      })
    },
    getSaveParam (id, tabs, filter = false) {
      let routeData = JSON.parse(JSON.stringify(tabs))
      let param = {
        'id': id || 0,
        'optPatternList': routeData
      }
      for (let tab of routeData) {
        let devs = tab.devs
        for (let inter of devs) {
          let patternList = inter.patternList.map(item => {
            let pattern = {
              'id': item.id,
              'desc': item.desc,
              'offset': item.offset,
              'cycle': item.cycle,
              'rings': item.rings
            }
            return pattern
          })
          inter.patternList = patternList
          // inter.id = param.id
          // delete inter.name
          // delete inter.content
          let dev = {
            'id': inter.id,
            'name': inter.name,
            'isused': inter.isused,
            'agentid': inter.agentid,
            'nextDistance': inter.nextDistance,
            'distance': inter.distance,
            'type': inter.type,
            'jsonparam': inter.jsonparam,
            'description': inter.description,
            'forwardphaseDesc': inter.forwardphaseDesc,
            'backphaseDesc': inter.backphaseDesc,
            'forwardphaseid': inter.forwardphaseid,
            'forwardphasedirection': inter.forwardphasedirection,
            'backphaseid': inter.backphaseid,
            'backphasedirection': inter.backphasedirection,
            'patternList': inter.patternList
          }
          inter = {...dev}
        }
      }
      if (filter) {
        param.optPatternList = param.optPatternList.map(pattern => {
          delete pattern.content
          delete pattern.date
          delete pattern.day
          delete pattern.direction
          delete pattern.downspeed
          delete pattern.keyintsid
          delete pattern.month
          delete pattern.optstrategy
          delete pattern.plan
          delete pattern.upspeed
          pattern.name = pattern.title
          // delete pattern.name
          // delete pattern.name
          delete pattern.title
          delete pattern.patternid
          pattern.devs.map(inter => {
            delete inter.allPatterns
            delete inter.currPhase
            delete inter.patternList
            delete inter.phaseList
            delete inter.ringCount
            delete inter.rings
          })
          return pattern
        })
      }
      return param
    },
    handleCreate (routeData) {
      let param = this.getGenerateParam(routeData, 1)
      generateRoute(param).then(res => {
        if (!res.data.success) {
          let msg = getMessageByCode(res.data.code, this.$i18n.locale)
          if (res.data.data) {
            let errorCode = res.data.data.errorCode
            if (errorCode) {
              msg = msg + ' - ' + getMessageByCode(errorCode, this.$i18n.locale)
            }
          }
          this.$message.error(msg)
          return
        }
        this.$message.success(this.$t('openatccomponents.greenwaveoptimize.generatesuedsucc'))
        this.greenwave = res.data.data.greenwave
        this.patternList = res.data.data.devs
        for (let dev of routeData.devs) {
          for (let pattern of this.patternList) {
            if (dev.agentid === pattern.agentid) {
              dev.feature = pattern.feature
              dev.patternid = pattern.patternid
            }
          }
        }
        this.handlePlanChart()
        this.handlePatternTable()
      })
    },
    getGenerateParam (routeData, bizType = 0) { // bizType： 1 generate专用
      let route = JSON.parse(JSON.stringify(routeData))
      let param = {
        'id': route.id,
        'name': route.name,
        'keyintsid': route.keyintsid,
        'direction': route.direction,
        'optstrategy': route.optstrategy,
        'upspeed': route.upspeed,
        'downspeed': route.downspeed,
        'type': route.type ? route.type : 0,
        'devs': route.devs
      }
      let devs = route.devs
      for (let inter of devs) {
        let patternList = inter.patternList.map(item => {
          let pattern = {
            'id': item.id,
            'desc': item.desc,
            'offset': item.offset,
            'cycle': item.cycle,
            'rings': item.rings
          }
          return pattern
        })
        let phaseList = inter.phaseList.map(item => {
          let pattern = {
            'id': item.id,
            'concurrent': item.concurrent
          }
          return pattern
        })
        let feature = {
          patternList: patternList,
          phaseList: phaseList
        }
        inter.routeid = param.id
        inter.feature = feature
        delete inter.id
        delete inter.name
      }
      // param = route
      param.devs = param.devs.map((item, index) => {
        let dev = {
          'agentid': item.agentid,
          'routeid': item.routeid,
          'forwardphaseid': item.forwardphaseid,
          'backphaseid': item.backphaseid,
          'distance': item.distance,
          'width': item.width,
          'sortid': item.sortid ? item.sortid : index + 1,
          'patternid': item.patternid,
          'feature': item.feature
        }
        if (bizType === 1) {
          dev.feature.patternList = dev.feature.patternList.filter(pattern => pattern.id === dev.patternid)
        }
        return dev
      })
      return param
    },
    closeDrawer (isRefresh) {
      this.configurationVisible = false
      if (isRefresh === 'refresh') {
        this.$emit('resetContentComponent')
      }
    },
    clickMask () {
      this.maskVisible = false
    },
    getAllPatternOfRoute () {
      if (this.agentids.length === 0) return
      console.log('this.routeData', this.routeData)
      getAllPatternOfDevs(this.agentids).then(res => {
        if (!res.data.success) {
          let agentid = res.data.data.agentid
          let commomMsg = this.$t('openatccomponents.greenwaveoptimize.device') + agentid
          let data = res
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
            }
          } else {
            this.$message.error(parrenterror + ',' + commomMsg)
          }
          this.$emit('ErrorOcurrred')
          return
        }
        this.allPatternList = res.data.data.devs
        let editableTab = this.routeData
        let patternList = this.getPatternListFromTab(editableTab, this.allPatternList)
        this.patternList = patternList
        this.getAllPhaseOfRouter() // 获取改路线的所有相位
      })
    },
    getAllPhaseOfRouter () {
      if (this.agentids.length === 0) return
      console.log('this.routeData', this.routeData)
      getAllPhaseOfDevs(this.agentids).then(res => {
        if (!res.data.success) {
          let agentid = res.data.data.agentid
          let commomMsg = this.$t('openatccomponents.greenwaveoptimize.device') + agentid
          let data = res
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
            }
          } else {
            this.$message.error(parrenterror + ',' + commomMsg)
          }
          this.$emit('ErrorOcurrred')
          return
        }
        this.allPhaseList = res.data.data.devs
        let editableTab = this.routeData
        let list = this.getPhaseListFromTab(editableTab, this.allPhaseList)
        this.phaseList = list
        // this.phaseList = res.data.data.devs
        this.handlePatternTable()
        this.handlePlanChart()
        this.handleMaskVisible()
      })
    },
    handlePatternTable () {
      this.$emit('handlePatternTable', this.routeData, this.patternList, this.phaseList)
      // let patterntable = this.$refs.patterntable
      // patterntable.onPatternTable(this.routeData, this.patternList, this.phaseList)
    },
    handlePlanChart () {
      this.$emit('handlePlanChart', this.routeData, this.patternList, this.greenwave, this.allPatternList)
      // let planchart = this.$refs.planchart
      // planchart.onPlanChart(this.routeData, this.patternList, this.greenwave)
    },
    handleMaskVisible () {
      // 数据为空，显示蒙层
      if (this.patternList && !this.patternList.length && this.step) {
        this.maskVisible = true
        // 模拟一次手动点击，触发tip显示
        this.$refs.editbtn.click()
      }
    },
    onNewPatternListChange (newPatternList) {
      this.refreshChart()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
